import router from './router/index.js';
import { API_BASE_URL } from './config.js';

const app = Vue.createApp({
  data() {
    return {
      activeMenu: '探索',
      menuItems: [
        { title: '探索', icon: 'Compass', path: '/explore' },
        { title: '好友', icon: 'UserFilled', path: '/friends' },
        { title: '聊天', icon: 'ChatDotRound', path: '/chat' },
        { title: '广场', icon: 'Grid', path: '/square' },
      ],
      isLoggedIn: false,
      userInfo: null,
      loginDialogVisible: false,
      registerDialogVisible: false,
      loginForm: {
        username: '',
        password: ''
      },
      registerForm: {
        username: '',
        password: '',
        confirmPassword: ''
      },
      loginRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      registerRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        confirmPassword: [{ 
          required: true, 
          validator: (rule, value, callback) => {
            if (value !== this.registerForm.password) {
              callback(new Error('两次输入的密码不一致'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }]
      }
    }
  },
  template: `
    <el-container class="layout-container">
      <!-- 侧边栏 -->
      <el-aside width="200px">
        <div class="logo" @click="goHome">AvatarChat</div>
        <el-menu
          :default-active="activeMenu"
          class="side-menu"
          router>
          <!-- 主菜单项容器 -->
          <div class="menu-items-container">
            <el-menu-item 
              v-for="item in menuItems" 
              :key="item.title" 
              :index="item.path"
              @click="handleSelect(item.title)">
              <el-icon><component :is="item.icon"/></el-icon>
              <span>{{item.title}}</span>
            </el-menu-item>
          </div>
          <!-- 化身菜单项 -->
          <div class="avatar-container">
            <el-menu-item 
              index="/my-avatar"
              @click="handleSelect('我的化身')"
              class="avatar-menu-item">
              <el-icon><Avatar /></el-icon>
              <span>我的化身</span>
            </el-menu-item>
          </div>
        </el-menu>
      </el-aside>

      <!-- 主要内容区 -->
      <el-container>
        <el-header height="60px">
          <div class="header-right">
            <!-- 未登录状态 -->
            <template v-if="!isLoggedIn">
              <el-button type="text" @click="loginDialogVisible = true">登录</el-button>
              <el-button type="primary" @click="registerDialogVisible = true">注册</el-button>
            </template>
            
            <!-- 已登录状态 -->
            <el-dropdown v-else @command="handleCommand">
              <span class="user-profile">
                <el-avatar :size="32" :src="userInfo?.avatar">{{ userInfo?.username?.charAt(0) }}</el-avatar>
                {{ userInfo?.username }}
                <el-icon><CaretBottom /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人主页</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>

      <!-- 登录对话框 -->
      <el-dialog v-model="loginDialogVisible" title="登录" width="30%">
        <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-width="0">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="用户名">
              <template #prefix><el-icon><User /></el-icon></template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="密码">
              <template #prefix><el-icon><Lock /></el-icon></template>
            </el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="loginDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleLogin">登录</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 注册对话框 -->
      <el-dialog v-model="registerDialogVisible" title="注册" width="30%">
        <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" label-width="0">
          <el-form-item prop="username">
            <el-input v-model="registerForm.username" placeholder="用户名">
              <template #prefix><el-icon><User /></el-icon></template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="registerForm.password" type="password" placeholder="密码">
              <template #prefix><el-icon><Lock /></el-icon></template>
            </el-input>
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input v-model="registerForm.confirmPassword" type="password" placeholder="确认密码">
              <template #prefix><el-icon><Lock /></el-icon></template>
            </el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="registerDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleRegister">注册</el-button>
          </div>
        </template>
      </el-dialog>
    </el-container>
  `,
  methods: {
    handleSelect(key) {
      this.activeMenu = key;
    },
    goHome() {
      this.$router.push('/');
      this.activeMenu = '';
    },
    async handleLogin() {
      try {
        const formData = new FormData();
        formData.append('username', this.loginForm.username);
        formData.append('password', this.loginForm.password);
        
        console.log('Sending login request to:', `${API_BASE_URL}/api/token`);
        
        const response = await fetch(`${API_BASE_URL}/api/token`, {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
          },
          body: formData
        });

        console.log('Response status:', response.status);
        const responseData = await response.json();
        console.log('Response data:', responseData);

        if (response.ok) {
          localStorage.setItem('token', responseData.access_token);
          this.userInfo = responseData.user;
          this.isLoggedIn = true;
          this.loginDialogVisible = false;
          this.$message.success('登录成功');
          
          this.loginForm = {
            username: '',
            password: ''
          };
        } else {
          this.$message.error(responseData.detail || '登录失败');
        }
      } catch (error) {
        console.error('Login error details:', error);
        this.$message.error('登录失败，请稍后重试');
      }
    },
    async handleRegister() {
      try {
        // 先验证表单
        await this.$refs.registerFormRef.validate();
        
        // 验证通过后再发送请求
        const response = await fetch(`${API_BASE_URL}/api/register`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          body: JSON.stringify({
            username: this.registerForm.username,
            password: this.registerForm.password
          })
        });

        if (response.ok) {
          this.registerDialogVisible = false;
          this.$message.success('注册成功，请登录');
          this.loginDialogVisible = true;
          
          this.registerForm = {
            username: '',
            password: '',
            confirmPassword: ''
          };
        } else {
          const error = await response.json();
          this.$message.error(error.detail || '注册失败');
        }
      } catch (error) {
        // 如果是表单验证错误，不显示"注册失败"
        if (error.message !== 'Validation Error') {
          console.error('Register error:', error);
          this.$message.error('注册失败，请稍后重试');
        }
      }
    },
    async handleCommand(command) {
      if (command === 'logout') {
        localStorage.removeItem('token');
        this.isLoggedIn = false;
        this.userInfo = null;
        this.$router.push('/');
        this.$message.success('已退出登录');
      } else if (command === 'settings') {
        this.$router.push('/settings');
      } else if (command === 'profile') {
        this.$router.push('/profile');
      }
    },
    // 检查登录状态
    async checkLoginStatus() {
      const token = localStorage.getItem('token');
      if (token) {
        try {
          const response = await fetch(`${API_BASE_URL}/api/users/me`, {
            headers: {
              'Authorization': `Bearer ${token}`,
              'Accept': 'application/json'
            }
          });
          
          console.log('Check login status response:', response.status);
          const data = await response.json();
          console.log('User data:', data);

          if (response.ok) {
            this.isLoggedIn = true;
            this.userInfo = data;
          } else {
            localStorage.removeItem('token');
            this.isLoggedIn = false;
            this.userInfo = null;
          }
        } catch (error) {
          console.error('Check login status error:', error);
          localStorage.removeItem('token');
          this.isLoggedIn = false;
          this.userInfo = null;
        }
      }
    }
  },
  mounted() {
    this.checkLoginStatus();
  }
});

// 使用路由
app.use(router);

// 注册Element Plus
app.use(ElementPlus, {
  locale: ElementPlusLocaleZhCn
});

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 挂载应用
app.mount('#app'); 